# -*- coding: utf-8 -*-
import json
import logging

from common import orm
from common.utils.decorator import sql_wrapper
from common.utils.db import list_object, get, upsert, delete
from common.preset.model.preset import Reward, RewardLimit
from common.utils.tz import to_ts

_LOGGER = logging.getLogger(__name__)


@sql_wrapper
def get_reward(id):
    return get(Reward, id)


def valid_condition(condition, term):
    def _valid_range_or_value(case, conds):
        if case in conds:
            return True
        for cond in conds:
            if (cond, list) and len(cond) == 2:
                if cond[0] <= case <= cond[1]:
                    return True
        return False

    condition = json.loads(condition or '{}')
    for k, v in condition.iteritems():
        if k == 'term':
            if not _valid_range_or_value(term, v):
                return False

    return True


def check_reward(activity_type, term, bet_type):
    def _calc_stats(rewards, hits):
        for reward in rewards:
            if not valid_condition(reward.condition, term):
                continue
            hits.append(reward.as_dict())
    hits = []
    # 全局配置
    rewards = Reward.query.filter(
        Reward.activity_type == 0).filter(
        Reward.enable == True).all()
    _calc_stats(rewards, hits)
    # 该彩种的全局配置
    rewards = Reward.query.filter(
        Reward.activity_type == activity_type).filter(
        Reward.bet_type == 0).filter(
        Reward.enable == True).all()
    _calc_stats(rewards, hits)
    # 具体的玩法配置
    rewards = Reward.query.filter(
        Reward.activity_type == activity_type).filter(
        Reward.bet_type == bet_type).filter(
        Reward.enable == True).all()
    _calc_stats(rewards, hits)

    return hits


@sql_wrapper
def get_reward_config(activity_type, term, bet_type):
    hits = check_reward(activity_type, term, bet_type)
    rate = amount = 0
    for hit in hits:
        # 这里不考虑限额的问题
        rate += hit['rate']
        amount += hit['amount']
    return rate, amount


@sql_wrapper
def add_reward_limit(title, left):
    """注意同时要设置redis中的limit，这个数据理论上是只能写一次的
    """
    assert left > 0
    limit = RewardLimit()
    limit.title = title
    limit.total = left
    limit.left = left
    limit.save()
    return limit


@sql_wrapper
def update_reward_limit(id, left):
    assert left >= 0
    limit = RewardLimit.query.with_for_update().filter(
        RewardLimit.id == id).one()
    if limit.left < left:   # 即又增加了资金
        limit.total += (left - limit.left)
    elif limit.left > limit:  # 即减少了资金
        limit.total -= (limit.left - left)

    limit.left = left
    limit.save()
    if left == 0:
        Reward.query.filter(
            Reward.limit == id).update({
                'enable': False
            })
        orm.session.commit()


@sql_wrapper
def upsert_reward(info, id=None):
    return upsert(Reward, info, id)


@sql_wrapper
def list_reward(query_dct):
    return list_object(query_dct, Reward)


@sql_wrapper
def delete_reward(id):
    delete(Reward, id)
